package cn.itcast.tlias.com.tliaswork.service.impl;

import cn.itcast.tlias.com.tliaswork.aop.MyLog;
import cn.itcast.tlias.com.tliaswork.mapper.DeptMapper;
import cn.itcast.tlias.com.tliaswork.mapper.EmpMapper;
import cn.itcast.tlias.com.tliaswork.pojo.Dept;
import cn.itcast.tlias.com.tliaswork.pojo.DeptLog;
import cn.itcast.tlias.com.tliaswork.service.DeptService;
import cn.itcast.tlias.com.tliaswork.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired(required = false)
    private DeptMapper deptMapper;

    @Autowired(required = false)
    private EmpMapper empMapper;


    @Autowired
    private LogService deptLogeService;
    /**
     * 查询全部的部门方法
     * @return
     */
    @Override
 //   @MyLog
    public List<Dept> list() {
        return deptMapper.list();
    }

    /**
     * 删除部门的同时还需要删除部门的员工
     * @param id
     */
//    @Transactional //交给Spring做事务管理
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(int id) {
        Dept dept= deptMapper.searchDeptById(id);

        try {
            deptMapper.deleteId(id);
            int i = 1 / 0;
            empMapper.deleteByDeptId(id);
        } finally {
            //日志记录,当其他事务回滚的时候,当前事务应该被记录
            //解散部门无论成功还是失败,都要记录操作日志
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部分的操作，此次解散的是"+dept.getName()+"部门");
            deptLogeService.insert(deptLog);
        }

    }

    @Override
    public void add(Dept dept) {
        //TODO：补全数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public void update(Dept dept) {
        //调整数据
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
